﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BL.Entities;
using System.Data.OleDb;



namespace zCO
{
    public partial class frmListaPrestaciones : Form
    {
        string starkey = " ";
        string halfStarkey = " ";
        public frmListaPrestaciones()
        {
            InitializeComponent();
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            //ColeccionObrasSociales obras = new ColeccionObrasSociales();
            //if (textBox1.Text != "")
            //{
            //    obras = ColeccionObrasSociales.LoadObraSocial(textBox1.Text);
            //}
            //foreach (ObraSocial o in obras)
            //{

            //    textBox1.AutoCompleteCustomSource.Add(o.NombreObra);

            //}

        }

        //private void textBox2_TextChanged(object sender, EventArgs e)
        //{
        //  ColeccionProfesionales prof = new ColeccionProfesionales();
        //    if (textBox2.Text != "")
        //    {
        //        prof = ColeccionProfesionales.LoadProfesional(textBox2.Text);
        //    }
        //    foreach (Profesionales p in prof)
        //    {

        //        textBox2.AutoCompleteCustomSource.Add(p.Apellido.ToString());

        //    }


        //}

        private void button1_Click(object sender, EventArgs e)
        {
            CargarGrilla();
        }


        private void button3_Click(object sender, EventArgs e)
        {
            UpdateGrilla();
        }
        private void CargarGrilla()
        {
            ColeccionIntervenciones inter = new ColeccionIntervenciones();
            DataTable dt = new DataTable();
            dataGridView1.Rows.Clear();
            string NombreObra = textBox1.Text;
            string matricula = textBox2.Text;
            string paciente = textBox3.Text;
            DateTime fechaIni = dateTimePicker1.Value.Date;
            DateTime fechaEnd = dateTimePicker2.Value.Date;
            string estado = comboBox1.Text;
            string abonada = comboBox2.Text;
            DateTime fechaLiqIni = DateTime.MinValue;
            DateTime fechaLiqEnd = DateTime.MaxValue;
            Double totalFinal=0;
            if (checkBox1.Checked == true)
            {
                fechaLiqIni = dateTimePicker3.Value.Date;
                fechaLiqEnd = dateTimePicker4.Value.Date;
                inter = ColeccionIntervenciones.LoadObraSocial(NombreObra, matricula,paciente, estado, abonada, fechaIni, fechaEnd, fechaLiqIni, fechaLiqEnd);
            }
            else
            {
                inter = ColeccionIntervenciones.LoadObraSocial(NombreObra, matricula,paciente, estado, abonada, fechaIni, fechaEnd);
            }
            int count = inter.Count;
            int index = 0;
            Double total = 0;
            foreach (Intervenciones i in inter)
            {


                if (i.Abonada == "True")
                {
                    i.Abonada = "Si";
                }
                else
                {
                    i.Abonada = "No";
                }

                if (index != 0 && dataGridView1.Rows[index - 1].Cells[1].Value.ToString() != starkey && i.Matricula != Int32.Parse(dataGridView1.Rows[index - 1].Cells[1].Value.ToString()))
                {
                    string mat = dataGridView1.Rows[index - 1].Cells[1].Value.ToString();

                    dataGridView1.Rows.Add(starkey, starkey, halfStarkey + halfStarkey, halfStarkey + halfStarkey, starkey, starkey, starkey, "TOTAL " + dataGridView1.Rows[index - 1].Cells[2].Value.ToString(), total, starkey, starkey, starkey, starkey);
                    total = 0;
                    for (int a = 0; a < 13; a++)
                    {
                        if (a == 7 || a == 8)
                            dataGridView1.Rows[index].Cells[a].Style.BackColor = Color.ForestGreen;
                        else
                            dataGridView1.Rows[index].Cells[a].Style.BackColor = Color.DarkGray;

                    }
                    index++;
                }
                dataGridView1.Rows.Add(i.NombreObraSocial, i.Matricula, i.Apellido + i.Nombre, i.ApellidoAfiliado.ToUpper() + " " + i.NombreAfiliado, i.NumeroAfiliado, i.IdPrestacion, i.Elemento, i.Cara, i.Arancel, i.Estado, i.Abonada, i.Fecha.Substring(0, 10),i.Detalle, i.IdIntervencion);
                total += Double.Parse(dataGridView1.Rows[index].Cells[8].Value.ToString());
                index++;
            }
            if (index != 0 && dataGridView1.Rows[index - 1].Cells[1].Value.ToString() != starkey)
            {
                string matt = dataGridView1.Rows[index - 1].Cells[1].Value.ToString();

                dataGridView1.Rows.Add(starkey, starkey, halfStarkey + halfStarkey, halfStarkey + halfStarkey, starkey, starkey, starkey, "TOTAL "+dataGridView1.Rows[index - 1].Cells[2].Value.ToString(), total, starkey, starkey, starkey,starkey);
                for (int a = 0; a < 13; a++)
                {
                    if (a == 7 || a == 8)
                        dataGridView1.Rows[index].Cells[a].Style.BackColor = Color.ForestGreen;
                    else
                        dataGridView1.Rows[index].Cells[a].Style.BackColor = Color.DarkGray;

                }
            }
            foreach (Intervenciones i in inter)
            {
                totalFinal += Double.Parse(i.Arancel);

            }
            if (index != 0)
            {
                dataGridView1.Rows.Add(starkey, starkey, halfStarkey + halfStarkey, halfStarkey + halfStarkey, starkey, starkey, starkey, "TOTAL GENERAL", totalFinal, starkey, starkey, starkey, starkey);
                for (int a = 0; a < 13; a++)
                {
                    if (a == 7 || a == 8)
                        dataGridView1.Rows[index + 1].Cells[a].Style.BackColor = Color.IndianRed;
                    else
                        dataGridView1.Rows[index + 1].Cells[a].Style.BackColor = Color.IndianRed;

                }
            }
        }

        private void UpdateGrilla()
        {
            ColeccionIntervenciones inter = new ColeccionIntervenciones();
            int matr;
            string numafi;
            int idPrest;
            string elem;
            string cara;
            string nomO;
            string abnd;
            string estd;
            DateTime fech;
            int idInt;
            string detalle;
            for (int i = 0; i < (dataGridView1.Rows.Count - 1); i++)
            {

               
                if (dataGridView1.Rows[i].Cells[0].Value.ToString() != starkey)
                {
                    nomO = dataGridView1.Rows[i].Cells[0].Value.ToString();
                    matr = Int32.Parse(dataGridView1.Rows[i].Cells[1].Value.ToString());
                    numafi = dataGridView1.Rows[i].Cells[4].Value.ToString();
                    idPrest = Int32.Parse(dataGridView1.Rows[i].Cells[5].Value.ToString());
                    elem = dataGridView1.Rows[i].Cells[6].Value.ToString();
                    cara = dataGridView1.Rows[i].Cells[7].Value.ToString();
                    estd = dataGridView1.Rows[i].Cells[9].Value.ToString().Substring(0, 1).ToUpper() + dataGridView1.Rows[i].Cells[9].Value.ToString().Substring(1);
                    abnd = dataGridView1.Rows[i].Cells[10].Value.ToString().Substring(0, 1).ToUpper() + dataGridView1.Rows[i].Cells[10].Value.ToString().Substring(1); 
                    fech = DateTime.Parse(dataGridView1.Rows[i].Cells[11].Value.ToString());
                    detalle = dataGridView1.Rows[i].Cells[12].Value.ToString();
                    idInt = Int32.Parse(dataGridView1.Rows[i].Cells[13].Value.ToString());
                    if (estd != "Aceptada" && estd != "Debitada")
                    {
                        MessageBox.Show("El campo: Estado debe ser igual a Aceptada o Debitada");
                        for (int e = 0; e <= 12; e++)
                        {
                            dataGridView1.Rows[i].Cells[e].Style.BackColor = Color.IndianRed;
                        }
                            return;
                    }
                    if (abnd != "Si" && abnd != "No")
                    {
                        MessageBox.Show("El campo: Abonada debe ser igual a Si o No");
                        for (int e = 0; e <= 12; e++)
                        {
                            dataGridView1.Rows[i].Cells[e].Style.BackColor = Color.IndianRed;
                        }
                        return;
                    }
                    ColeccionIntervenciones.UpdateObra(nomO, matr, numafi, idPrest, elem, cara, estd, abnd, fech,detalle, idInt);
                }
            }
            CargarGrilla();
            MessageBox.Show("Campos actualizados con exito");
        
        }

        private void frmListaPrestaciones_FormClosing(object sender, FormClosingEventArgs e)
        {
            DialogResult dr = MessageBox.Show("¿Desea guardar los cambios?", "Modificar Intervenciones", MessageBoxButtons.YesNoCancel);
            switch (dr)
            {
                case DialogResult.Abort:
                    break;
                case DialogResult.Cancel:
                    e.Cancel = true;
                    break;
                case DialogResult.Ignore:
                    break;
                case DialogResult.No:
                    break;
                case DialogResult.None:
                    break;
                case DialogResult.OK:
                    break;
                case DialogResult.Retry:
                    break;
                case DialogResult.Yes:
                    UpdateGrilla();
                    e.Cancel = false;

                    break;
                default:
                    break;
            }
        }

        private void cmdPrint_Click(object sender, EventArgs e)
        {
            Excel.Imprimir(dataGridView1, true);
        }

        private void cmdExcel_Click(object sender, EventArgs e)
        {
            //Excel.export(dataGridView1, true);
            try
            {
                DateTime fech = DateTime.Parse(dataGridView1.Rows[0].Cells[11].Value.ToString());
                Excel.generateExcelFromFile(dataGridView1, false, true, textBox1.Text, fech.ToString("MMMM").ToUpper(), fech.ToString("yyyy"));
            }
            catch (Exception)
            {
                //Probablemente cerraron el excel, habria q mejorar el control de errores ....
                
            }
            
        }

        private void frmListaPrestaciones_Load(object sender, EventArgs e)
        {

            textBox1.AutoCompleteMode = AutoCompleteMode.Append;
            textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
            textBox2.AutoCompleteMode = AutoCompleteMode.Append;
            textBox2.AutoCompleteSource = AutoCompleteSource.CustomSource;
            textBox3.AutoCompleteMode = AutoCompleteMode.Append;
            textBox3.AutoCompleteSource = AutoCompleteSource.CustomSource;

            foreach (var item in ColeccionObrasSociales.Current) {
                textBox1.AutoCompleteCustomSource.Add(item.NombreObra.ToUpper());
            }
                        
            foreach (var item in ColeccionProfesionales.Current)
            {
                if (item.Activo == true)
                {
                    textBox2.AutoCompleteCustomSource.Add(item.Apellido.ToUpper());
                }
            }

            foreach (var item in ColeccionPacientes.Current)
            {
                
                    textBox3.AutoCompleteCustomSource.Add(item.Apellido.ToUpper());
            }



        }

        private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {

            DataGridViewTextBoxEditingControl te = (DataGridViewTextBoxEditingControl)e.Control;
            te.AutoCompleteMode = AutoCompleteMode.Append;
            te.AutoCompleteSource = AutoCompleteSource.CustomSource;
            int i = 0;
            if (e.Control is DataGridViewTextBoxEditingControl && ((DataGridView)sender).CurrentCell.ColumnIndex == 9)
            {
                string[] est = new string[2];
                est[0] = "Aceptada";
                est[1] = "Debitada";
                foreach (string item in est)
                {
                    if (item != null)
                    {
                        
                        
                        te.AutoCompleteCustomSource.Add(est[i]);
                        i++;
                    }
                }
            }
            if (e.Control is DataGridViewTextBoxEditingControl && ((DataGridView)sender).CurrentCell.ColumnIndex == 10)
            {
                string[] abo = new string[2];
                abo[0] = "Si";
                abo[1] = "No";
                foreach (string item in abo)
                {
                    if (item != null)
                    {


                        te.AutoCompleteCustomSource.Add(abo[i]);
                        i++;
                    }
                }
            }
            
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox1.Checked == true)
            {
                dateTimePicker3.Visible = true;
                dateTimePicker4.Visible = true;
                label8.Visible = true;
                label9.Visible = true;
            }
            else
            {
                dateTimePicker3.Visible = false;
                dateTimePicker4.Visible = false;
                label8.Visible = false;
                label9.Visible = false;
            }
            }

      


       

     



    }
}
